﻿<%@ WebHandler Language="C#" Class="HandlerMainPage" %>

using System;
using System.Web;
using System.Linq;
using Newtonsoft.Json;

public class HandlerMainPage : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {

        UboxContext dc = new UboxContext();

        int page = 1;
        int cate = 0;
        int brand = 0;
        string find = "0";
        int itemCount = 12;
        
        if (context.Request.QueryString["uPage"] != null)
        {
            page = Convert.ToInt32(context.Request.QueryString["uPage"]);
        }
        if (context.Request.QueryString["uCate"] != null)
        {
            cate = Convert.ToInt32(context.Request.QueryString["uCate"]);
        }
        if (context.Request.QueryString["uBrand"] != null)
        {
            brand = Convert.ToInt32(context.Request.QueryString["uBrand"]);
        }
        if (context.Request.QueryString["uFind"] != null)
        {
            find = context.Request.QueryString["uFind"];
        }
        
        var ubox = (from a in dc.unboxing_article
                                join i in dc.unboxing_image
                                on a.unboxing_article_id equals i.unboxing_article_id into buf
                                from i in buf.DefaultIfEmpty()
                                join p in dc.production_product
                                on a.product_id equals p.product_id
                                where (a.unboxing_visible == true)  &&
                                (cate ==0 ? true : p.category_id==cate ) &&
                                (brand == 0 ? true : p.brand_id==brand )  &&
                                (find == "0"? true: a.unboxing_article_title.Contains(find))
                                orderby a.unboxing_article_publish_date descending
                                select new
                                {
                                    uboxId = a.unboxing_article_id,
                                    uboxTitle = a.unboxing_article_title,
                                    productId = a.product_id,
                                    productCate = p.category_id,
                                    productBrand = p.brand_id,
                                    uboxImg = i.image
                                }).Skip((page - 1) * itemCount).Take(itemCount);

        context.Response.ContentType = "application/json";
        context.Response.Write(JsonConvert.SerializeObject(ubox));

        dc.Dispose();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}